import React, { Fragment, useEffect, useState } from 'react';
import { connect } from 'umi';
import { Card, Form, Table, Input, TreeSelect, DatePicker } from 'antd';
import PageRouter from '@/components/PageRouter/PageRouter';
import styles from '@/pages/Flow/Mine/WaitApproval/index.less';
import ProxyModal from '@/pages/Flow/Mine/WaitApproval/NewProxyModal';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Pagination from '@/components/Pagination';
import ApplyStatus from '@/components/ApplyStatus';
import xss from 'xss';
import LinkTo from '@/components/LinkTo';
import { AdvancedSearch, TableFilter } from '@/components';
import { getTreeData } from '@/utils/utils';

const { RangePicker } = DatePicker;
const { SHOW_ALL } = TreeSelect;

const List = ({ dispatch, flowMyAudited, loading, form, flowCommon }) => {
    const { pagination, myAuditedList } = flowMyAudited;

    const listLoading = loading;
    const [visible, setVisible] = useState(false);

    const { flowType = [], orderType, processStatusType = [] } = flowCommon;
    const { getFieldDecorator, getFieldsValue } = form;
    // 获取流程模板
    const fetchFlowTypeList = () => {
        dispatch({
            type: 'flowCommon/fetchFlowType',
            payload: {
                status: 2
            }
        });
    };
    const transformFilters = (data = []) =>
        data.map(item => ({
            text: item.dictName,
            value: item.dictValue
        }));
    const columns = [
        {
            title: '申请主题',
            dataIndex: 'processInstanceName',
            key: 'processInstanceName',
            width: '20%',
            render: (text, record) => (
                <LinkTo
                    to="/personal/portal/myAudited/myAuditedDetail"
                    query={{
                        taskId: record.taskId,
                        processInstanceName: record.processInstanceName,
                        processInstanceId: record.processInstanceId
                    }}
                >
                    {text}
                </LinkTo>
            )
        },
        {
            title: '摘要',
            dataIndex: 'applicationAbstract',
            key: 'applicationAbstract',
            render: text => <span style={{ wordBreak: 'break-all' }} dangerouslySetInnerHTML={{ __html: xss(text) }} />
        },
        {
            title: '发起时间',
            dataIndex: 'startTime',
            key: 'startTime',
            width: 200,
            sorter: () => {}
        },
        {
            title: '完成时间',
            dataIndex: 'endTime',
            key: 'endTime',
            width: 200,
            sorter: () => {}
        },
        {
            title: '状态',
            dataIndex: 'processStatus',
            key: 'processStatus',
            width: '15%',
            filters: transformFilters(processStatusType),
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            filterMultiple: false,
            render: (text, record) => {
                if (record.processCandidateUsers) {
                    return (
                        <div>
                            <ApplyStatus status={record.processStatus} />
                            {record.processCandidateUsers}-{record.processStatusName}
                        </div>
                    );
                }
                return (
                    <div>
                        <ApplyStatus status={record.processStatus} />
                        {record.processStatusName}
                    </div>
                );
            }
        }
    ];

    const fetchList = () => {
        const { processInstanceName = '', date = [], processDefinitionKeys = [] } = getFieldsValue();
        const params = {
            pageNo: pagination.current,
            pageSize: pagination.pageSize,
            processInstanceName,
            instStatus: flowCommon.instStatus,
            startTime: date[0] ? date[0].format('YYYY-MM-DD 00:00:00') : '',
            endTime: date[1] ? date[1].format('YYYY-MM-DD 23:59:59') : '',
            processDefinitionKeys,
            orderType
        };
        dispatch({
            type: 'flowMyAudited/fetch',
            payload: params
        });
    };
    const paginationChange = _pagination => {
        dispatch({ type: 'flowMyAudited/save', payload: { pagination: { ...pagination, ..._pagination } } });
    };
    // 表单搜索 重置表单
    const handleSubmit = async () => {
        if (pagination.current !== 1) {
            await dispatch({
                type: 'flowMyAudited/save',
                payload: {
                    pagination: {
                        ...pagination,
                        current: 1
                    }
                }
            });
        } else {
            fetchList();
        }
    };

    // 对后端返回的数据进行处理
    const getData = data => {
        if (!data || data.length === 0) return [];
        return getTreeData(
            data.map(item => ({
                ...item,
                processName: item.categoryName,
                processKey: item.category,
                children: item.workflowDefProcessDTOList || []
            })),
            {
                title: 'processName',
                value: 'processKey'
            }
        );
    };

    const tableChange = (_pagination, filters = {}, sorter) => {
        let instStatus = '';
        let orderBy;
        if (filters && filters.processStatus && filters.processStatus.length > 0) {
            // eslint-disable-next-line prefer-destructuring
            instStatus = filters.processStatus[0];
        }
        // 发起时间排序
        if (sorter && sorter.field === 'startTime') {
            if (sorter && sorter.order === 'ascend') {
                orderBy = 1;
            } else {
                orderBy = 2;
            }
        }
        // 完成时间排序
        if (sorter && sorter.field === 'endTime') {
            if (sorter && sorter.order === 'ascend') {
                orderBy = 3;
            } else {
                orderBy = 4;
            }
        }
        dispatch({
            type: 'flowCommon/save',
            payload: {
                instStatus,
                orderType: orderBy
            }
        });
        dispatch({
            type: 'flowMyAudited/save',
            payload: {
                pagination: { ...pagination, current: 1 }
            }
        });
    };
    // 获取状态
    const fetchProcessStatus = () => {
        dispatch({
            type: 'flowCommon/fetchProcessStatusType',
            payload: {
                code: 'processStatus'
            }
        });
    };
    useEffect(() => {
        fetchList();
    }, [pagination.current, pagination.pageSize, orderType, flowCommon.instStatus]);
    useEffect(() => {
        fetchFlowTypeList();
        fetchProcessStatus();
        return () => {
            dispatch({
                type: 'flowMyAudited/save',
                payload: {
                    pagination: {
                        ...pagination,
                        current: 1,
                        pageSize: 10
                    }
                }
            });
            dispatch({
                type: 'flowCommon/save',
                payload: {
                    orderType: '',
                    processStatusType: [],
                    instStatus: ''
                }
            });
        };
    }, []);
    return (
        <PageHeaderWrapper>
            <PageRouter type="flowMyflow" activePath="/personal/portal/myAudited/list">
                {isPageRouter => (
                    <Fragment>
                        <Card bordered={false} title={!isPageRouter && '经我审批'} className={styles.tableapproval}>
                            <AdvancedSearch onReset={handleSubmit} onSubmit={handleSubmit} form={form}>
                                <Form.Item label="标题">
                                    {getFieldDecorator('processInstanceName')(
                                        <Input placeholder="请输入主题" allowClear />
                                    )}
                                </Form.Item>
                                <Form.Item label="发起时间">{getFieldDecorator('date')(<RangePicker />)}</Form.Item>
                                <Form.Item label="申请类型">
                                    {getFieldDecorator('processDefinitionKeys')(
                                        <TreeSelect
                                            maxTagCount={1}
                                            treeCheckable
                                            showCheckedStrategy={SHOW_ALL}
                                            searchPlaceholder="请选择"
                                            treeData={getData(flowType)}
                                            allowClear
                                        />
                                    )}
                                </Form.Item>
                            </AdvancedSearch>
                            <Table
                                bordered={false}
                                columns={columns}
                                loading={listLoading}
                                dataSource={myAuditedList}
                                onChange={tableChange}
                                rowKey={record => record.taskId}
                                pagination={false}
                            />
                            <Pagination {...pagination} onChange={paginationChange} />
                        </Card>
                        <ProxyModal
                            visible={visible}
                            onOk={() => setVisible(false)}
                            onCancel={() => setVisible(false)}
                            width={900}
                        />
                    </Fragment>
                )}
            </PageRouter>
        </PageHeaderWrapper>
    );
};
export default connect(({ flowMyAudited, loading, flowCommon }) => ({
    flowCommon,
    flowMyAudited,
    loading: loading.effects['flowMyAudited/fetch']
}))(Form.create()(List));
